package com.woniuxy.woniuticket.movieinfomodule.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Utopia
 * @title: UploadImgController
 * @projectName woniuticket
 * @description: TODO
 * @date 2019/6/17 15:07
 */

@Controller
@RequestMapping("/imgUpload")
public class UploadImgController {

    @Value("${upload.location}")
    private String path;

    @RequestMapping("/insert")
    @ResponseBody
    public Object uploadImg(MultipartFile file){
        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        String newFileName = new SimpleDateFormat("yyyyMMddhhmmssSSS").format(new Date())+suffix;
        String url = null;
        try {
            url = ResourceUtils.getURL("classpath:").getPath();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        File f = new File(url+path);
        if (!f.exists()){
            f.mkdirs();
        }
        try {
            FileCopyUtils.copy(file.getBytes(),new File(f.getAbsolutePath(),newFileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        String relPath = path+newFileName;
        relPath = relPath.substring(relPath.indexOf("static")+"static".length());
        Map<String,Object> map = new HashMap<>();
        map.put("code",0);
        map.put("msg","上传成功！");
        map.put("data",relPath);

        return map;
    }

}
